package cn.xc.org.controller;

import cn.xc.basic.util.AjaxResult;
import cn.xc.basic.util.PageList;
import cn.xc.org.domain.Department;
import cn.xc.org.query.DepartmentQuery;
import cn.xc.org.service.IDepartmentService;
import cn.xc.system.annotation.PreAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(value = "部门api",description = "部门CRUD")
@RestController
@RequestMapping("/department")
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;

    @GetMapping
    @ApiOperation(value = "查询所有")
    public List<Department> findAll(){
        return departmentService.findAll();
    }

    @GetMapping("/deptTree")
    @ApiOperation(value = "查询部门数")
    public List<Department> deptTree(){
        return departmentService.deptTree();
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "查询单个对象")
    public Department findOne(@PathVariable("id") Long id){
        return  departmentService.findById(id);
    }

    @PostMapping
    @ApiOperation(value = "分页查询")
    @PreAuthorize(name = "部门列表",sn = "department:list")
    public PageList<Department> queryPage(@RequestBody  DepartmentQuery departmentQuery){
        return departmentService.queryPage(departmentQuery);
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除")
    public AjaxResult del(@PathVariable("id") Long id){
        try{
            departmentService.del(id);
            return new AjaxResult();
        }catch (Exception e){
            e.printStackTrace();
            return new AjaxResult(false,"删除失败");
        }
    }
    @PatchMapping
    @ApiOperation(value = "批量删除")
    public AjaxResult patchDel(@RequestBody List<Long> ids){
        try{
            departmentService.patchDel(ids);
            return new AjaxResult();
        }catch (Exception e){
            e.printStackTrace();
            return new AjaxResult(false,"删除失败");
        }
    }

    @PutMapping
    @ApiOperation(value = "添加和修改")
    public AjaxResult addOrUpdate(@RequestBody Department department){
        try{
            if(department.getId()==null){
                departmentService.add(department);
            }else{
                departmentService.update(department);
            }
            return new AjaxResult();
        }catch (Exception e){
            e.printStackTrace();
            return new AjaxResult(false,"操作失败");
        }
    }


}
